﻿using Sidvall.Serialization;
using System.Threading.Tasks;

namespace Sidvall.WorkItemManager.Workflow
{
    public static class WorkItemProviderFactory
    {
        #region CreateProviderAsync

        public static async Task<IWorkItemProvider> CreateProviderAsync(string[] args, long defaultWorkItemId, System.Func<IWorkItemProvider> createNewHandler)
        {
            long? workItemId;

            workItemId = null;
            if (args != null)
            {
                if (args.Length > 0)
                    workItemId = args[0].ToNullableInt64();
            }
            if (workItemId == null)
                workItemId = defaultWorkItemId;
            var workItem = await Sidvall.WorkItemManager.SystemContext.Current.DataPortal.WorkItemManager.GetItemByPrimaryKeyAsync(workItemId.Value).ConfigureAwait(false);
            var serverManager = await ServerManagerFactory.GetServerManagerAsync(null).ConfigureAwait(false);
            var workManagerTask = Sidvall.WorkItemManager.Workflow.WorkManagerTask.GetWorkManagerTask(serverManager, false, false, workItem);
            var workItemProvider = createNewHandler.Invoke();
            workItemProvider.ExecutionContext = workItem.ExecutionContext;
            workItemProvider.Manager = workManagerTask;
            await Sidvall.WorkItemManager.SystemContext.Current.DataPortal.WorkItemSensorManager.LoadSensorsAsync(workItemProvider, null, workItem.WorkItemId.Value).ConfigureAwait(false);
            return workItemProvider;
        }

        #endregion
    }
}
